package com.celesea.framework.jwt;

import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtCookieUtil {

    public static void create(HttpServletResponse httpServletResponse, String value, Boolean secure, Integer maxAge, String domain) {
        Cookie cookie = new Cookie(JwtUtil.JWT_TOKEN, value);
        cookie.setSecure(secure);
        cookie.setHttpOnly(true);
        cookie.setMaxAge(maxAge);
        cookie.setDomain(domain);
        cookie.setPath("/");
        httpServletResponse.addCookie(cookie);
    }

    public static void clear(HttpServletResponse httpServletResponse) {
        Cookie cookie = new Cookie(JwtUtil.JWT_TOKEN, null);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(0);
        httpServletResponse.addCookie(cookie);
    }

    public static String getValue(HttpServletRequest httpServletRequest) {
        Cookie cookie = WebUtils.getCookie(httpServletRequest, JwtUtil.JWT_TOKEN);
        return cookie != null ? cookie.getValue() : null;
    }
}
